package com.yhally.seata.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhally.seata.common.constants.NumberConstant;
import com.yhally.seata.order.dao.OrderDao;
import com.yhally.seata.order.domain.Order;
import com.yhally.seata.order.feign.AccountService;
import com.yhally.seata.order.feign.StorageService;
import com.yhally.seata.order.service.OrderService;
import com.yhally.seata.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 * @author wangyu
 * @version 1.0
 * @date 2022/5/6 23:00
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {


    private final OrderDao orderDao;
    private final AccountService accountService;
    private final StorageService storageService;
    private final OrderTccAction orderTccAction;

    @Override
    @GlobalTransactional(name = "seata-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("--------->开始新建订单");
        //1 新建订单
        order.setNo(IdUtil.getSnowflakeNextId());
        order.setStatus(NumberConstant.ONE);
        orderDao.create(order);
        //2 扣减库存
        log.info("------------->订单微服务开始调用库存,做扣减Count");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("------------->订单微服务开始调用库存,做扣减end");
        //3 扣减账户
        log.info("------------->订单微服务开始调用账户,做扣减Money");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("------------->订单微服务开始调用账户,做扣减end");

        //4 修改订单状态
        log.info("------------->修改订单状态开始");
        orderDao.updateOrder(order.getUserId(),0);
        log.info("------------->修改订单状态结束");

        log.info("------------->下订单结束了");
    }

    @Override
    @GlobalTransactional
    public void createByTcc(Order order) {
        // 创建订单
        order.setNo(IdUtil.getSnowflakeNextId());
        order.setStatus(NumberConstant.ZERO);
        orderTccAction.creatOrder(null,order);

        // 扣减库存
        storageService.decreaseByTcc(order.getProductId(),order.getCount());

        // TODO 扣减账户
    }
}
